var clientall=[];
var pinmingall=[];

$(function(){

    $("#billcodeDate").datebox("setValue", getDay(0));
    // $("#deliverydate").datebox("setValue", getDay(7));
    $("#billcode").textbox({disabled: true});

    getdropdownDataA();  //获取所有下拉数据

    setpinmingDW()

    // $('#A').window('close');

});
//解决数据异步问题
function setpinmingDW() {
    //设置品名下拉
    $.ajax({
        url: strLin + 'product/selectAll',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            pinmingall=cdata.data;

            setBillOrderDetail();  //初始化网格内容

            for (let i = 0; i < 12; i++) {
                $("#billgrid").edatagrid('appendRow', {});
            }
            bindEnterEvents();  //定回车焦点移动到下一个输入文本框中
        }
    });
}

//明细录入网格
function setBillOrderDetail() {
    $('#billgrid').edatagrid({
        data: [],
        singleSelect :true,   //如果为true，则只允许选择一行
        rownumbers:true,     //显示行号
        striped: true,
        fit: true,
        // autoSave: true,
        sortable: true,
        remoteSort: false,
        showFooter: true,
        height: 'auto',
        columns:[[
            {
                field:'iid',
                title:'明细主键',
                width:120,
                hidden:true,
                align:'center',
                editor: {type: "numberbox",options: {}}
            },
            {
                field:'product_sid',
                title:'品名',
                width:250,
                align:'center',
                // editor: {type: "textbox", options: {required: true}}
                editor: {
                    type: "combobox",
                    options: {
                        required: true,
                        valueField: 'sid',
                        textField: 'sid',
                        data:pinmingall
                    }
                }
            },
            {
                field:'color',
                title:'颜色',
                width:150,
                align:'center',
                editor: {type: "textbox", options: {required: true}}
            },
            // {
            //     field:'color_code',
            //     title:'色号',
            //     width:130,
            //     align:'center',
            //     editor: {type: "textbox", options: {}}
            // },
            {
                // field:'amount',
                field:'price',
                title:'单价',
                width:100,
                align:'right',
                editor: {type: "textbox", options: {}}
            },
            {
                field:'kilo',
                title:'重量',
                width:140,
                align:'right',
                formatter:function(value,rec){undefined
                    return rec.kilo>0?parseFloat(rec.kilo).toFixed(1):'';
                },
                editor: {type: "textbox", options: {required: true}}
            },

            {
                field:'remark',
                title:'备注',
                width:260   ,
                align:'center',
                editor: {type: "textbox", options: {}}
            },

        ]],
    onLoadSuccess: function (data) {
            compute();
            $(this).datagrid('resize');
        },
        onSave: function (index, row) {
            compute();
        },
        onDestroy: function (index, row) {
            compute();
        },
        onEdit: function (i, r) {
            index = i;
        },
        onSelect: function (i, d) {
            index = i;
        },
    });
}

//刷新
function reloadPM() {
    $("#billgrid").edatagrid("saveRow");
    let detailBill = $("#billgrid").edatagrid("getRows");

    getdropdownDataB();
    getdropdownDataA();

    $.ajax({
        url: strLin + 'product/selectAll',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            pinmingall=cdata.data;

            setBillOrderDetail();  //初始化网格内容
            console.log(detailBill);
            $("#billgrid").edatagrid('loadData', detailBill);

            bindEnterEvents();  //定回车焦点移动到下一个输入文本框中
        },
    });
}

//保存修改
function saveA() {
    $("#billgrid").edatagrid("saveRow");
    var strData=[];
    var etime = new Date();
    var m_date = format(etime);
    var m_billdate= $('#billcodeDate').datebox('getValue') + ' ' +getnewdatetime(etime);
    // var m_delivery_date = $('#deliverydate').datebox('getValue')+ ' ' +getnewdatetime(etime);
    console.log(m_date);
    console.log(m_date.substring(m_date.length-8,m_date.length));
    console.log(m_date.substring(0,10));

    var m_billcode = $("#billcode").textbox('getValue');
    var m_ddh = $("#ddh").textbox('getValue');
    var m_khname = $("#clientName").combobox('getText');
    var m_khid = $("#clientName").combobox('getValue');

    if (m_khname.length <= 0) {$.messager.alert('提示','客户为空，不允许保存！');return;}
    if (m_ddh.length <= 0) {$.messager.alert('提示','订单号为空，不允许保存！');return;}

    let detailBill = $("#billgrid").edatagrid("getRows");
    for (let i = 0; i < detailBill.length; i++) {
        if (detailBill[i].product_sid && detailBill[i].color && detailBill[i].kilo){
            if (detailBill[i].kilo>0){
            strData[i]=detailBill[i]
            }else{
                $.messager.alert('提示','重量为空或者小于等于0，不允许保存！');
                return;
            }

        }
    }
    if (strData.length==0){
        console.log('退出，不允许保存')
        $.messager.alert('提示','明细必输选项为空，不允许保存！')
        return;
    }

if (m_orderID==null) {
    var SQLstr = {
        "main": {
            "bill_date": m_billdate,
            // "delivery_date": m_delivery_date,
            "order_code": m_ddh,
            "client_sid": m_khid
        },
        "details": strData
    };
    console.log(SQLstr);
    $.ajax({
        url: strLin + 'billOrder/insert',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(SQLstr),
        contentType: "application/json;charset=UTF-8",
        success: function (data) {
            console.log('保存成功data');
            console.log(data);
            m_orderID = data.data.main.iid;
            console.log("m_orderID= " + m_orderID);
            $("#billcode").textbox('setValue', data.data.main.bill_code);
            $("#billgrid").edatagrid('loadData', data.data.details);
            $.messager.alert('提示', '保存成功！')
            setStatusA(1);
            Orderlocking();
            refresh();
            $("#saved").show();
            $("#audited").hide();
            $("#invalid").hide();
        }
    });
}else{
    var SQLstr2 = {
        "main": {
            "iid":m_orderID,
            "bill_date": m_billdate,
            // "delivery_date": m_delivery_date,
            "order_code": m_ddh,
            "client_sid": m_khid
        },
        "details": strData
    };
    console.log(SQLstr2);
    $.ajax({
        url: strLin + 'billOrder/update',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(SQLstr2),
        contentType: "application/json;charset=UTF-8",
        success: function (data) {
            console.log('修改保存成功data');
            console.log(data);
            m_orderID = data.data.main.iid;
            console.log("m_orderID= " + m_orderID);
            $("#billgrid").edatagrid('loadData', data.data.details);
            $.messager.alert('提示', '修改保存成功！')
            updateplanAll(m_orderID);
            setStatusA(1);
            Orderlocking();
            refresh();
            $("#saved").show();
            $("#audited").hide();
            $("#invalid").hide();
        }
    });
}

}

//修改订单之后 同步修改计划单
function updateplanAll(vOrderID) {
    $.ajax({
        url: strLin + 'dynamicQuery/callProc',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(['usp_updatePlan_order',vOrderID]),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            console.log('同步计划单完成！')
        }
    });
}

//打开订单
function openorderbillA(detailID) {
    $.ajax({
        url: strLin + 'billOrder/selectByPrimaryKey/'+ detailID,
        type: 'get',
        dataType: 'json',
        contentType: "application/json;charset=UTF-8",
        success: function (data) {
            console.log('openorderbillA：');
            console.log(data);
            m_orderID=data.data.main.iid;
            console.log("m_orderID= " + m_orderID);
            $("#billcodeDate").datebox("setValue", data.data.main.bill_date);
            // $("#deliverydate").datebox("setValue", data.data.main.delivery_date);
            $("#billcode").textbox('setValue',data.data.main.bill_code);
            $("#clientName").combobox('setValue',data.data.main.client_sid);
            $("#ddh").textbox('setValue',data.data.main.order_code);
            $("#billgrid").edatagrid('loadData', data.data.details);

            setStatusA(1);
            Orderlocking();
            $("#saved").show();
            // $("#audited").hide();
            // $("#invalid").hide();
        }
    });
}

//复制订单
function copyOrderbillA() {
    if (m_orderID == null) {
        $.messager.alert('提示','请打开有效单据，在进行复制！');
        return;
    }
    m_orderID = null;
    setStatusA(0);
    $("#billgrid").edatagrid('enableEditing');
    $("#clientName").combobox("enable");
    $("#ddh").textbox({disabled: false});
    $("#billcode").textbox('setValue','');

    $("#saved").hide();
    $("#audited").hide();
    $("#invalid").hide();
}

//修改订单
function updateorderbillA() {
    setStatusA(0);
    $("#billgrid").edatagrid('enableEditing');
    $("#clientName").combobox("enable");
    $("#ddh").textbox({disabled: false});
    $("#saved").hide();
    $("#audited").hide();
    $("#invalid").hide();
}

//作废单据
function deleteplanA() {
    $.messager.defaults = {ok: "确定", cancel: "取消", width: 300, closable: false};
    $.messager.confirm('确认', '您确认要作废当前单据吗？', function (r) {
        if (r) {

            $('#C').window('open');

        }
    });
}

//合计
function compute() {
    let rows = $("#billgrid").edatagrid("getRows");
    let number = 0, qty = 0, total = 0, meter = 0, kilo = 0;
    for (let i = 0; i < rows.length; i++) {
        // number += parseFloat(rows[i].amount ? rows[i].amount : 0);
        qty += parseFloat(rows[i].kilo ? rows[i].kilo : 0);

    }
    $("#billgrid").edatagrid('reloadFooter', [
        {
            product_sid: '合计',
            // amount: number.toFixed(0),
            kilo: qty.toFixed(1),
        }
    ]);
}

/* 清行 */
function btn_delete_line() {
    let billgridRow = $("#billgrid").edatagrid('getSelections');
    let billdetailID = billgridRow[0].iid;
    console.log(billgridRow);
    console.log(billdetailID);
    if (billdetailID==0 || billdetailID==undefined) {
        $("#billgrid").edatagrid('destroyRow');
    }else {
        $.messager.defaults = {ok: "确定", cancel: "取消", width: 300, closable: false};
        $.messager.confirm('确认', '当前删除为永久删除，不可恢复，确定删除吗？', function (r) {
            if (r) {
                // let billgridRow = $("#billgrid").edatagrid('getSelections');
                // let billdetailID = billgridRow[0].iid;
                console.log(billgridRow);
                console.log(billdetailID);
                $.ajax({
                    url: strLin + 'dynamicQuery/querySqlString/select iid from  plan where state=1 and parent_id=' + billdetailID,
                    type: 'get',
                    dataType: 'json',
                    success: function (cdata) {
                        let data = cdata.data;
                        console.log(data);
                        console.log(data.length);
                        if (data.length > 0) {
                            $.messager.show({title: "提示", msg: "当前订单颜色存在已生成计划单，不允许删除！"});
                            return true;
                        } else {
                            $.ajax({
                                url: strLin + 'orderDetail/delete/' + billdetailID,
                                    type: 'get',
                                    dataType: 'json',
                                    success: function (cdata) {
                                        $("#billgrid").edatagrid('destroyRow');
                                        console.log(cdate)
                                }
                            });
                            console.log('不存在计划')
                            return false;
                        }
                    }
                });
            }
        })
    }
}

/*新增行*/
function btn_add_line() {
    $('#billgrid').edatagrid('addRow');
}

/* 复制行 */
function btn_copy_line() {
    $("#billgrid").edatagrid("saveRow");
    let selected = $("#billgrid").edatagrid("getSelected");
    if (selected) {
        selected = JSON.parse(JSON.stringify(selected));
        selected['iid'] = 0;
        $("#billgrid").edatagrid("addRow", {index: index + 1, row: selected});
    } else {
        $.messager.show({title: "提示", msg: "请选择原始行以复制"});
    }
};


//订单模态窗清空所有内容，恢复到初始状态
function ClearallorderBill() {
    m_orderID=null;
    $("#billcodeDate").datebox("setValue", getDay(0));
    $("#deliverydate").datebox("setValue", getDay(7));
    $("#billcode").textbox('setValue','');
    $("#ddh").textbox('setValue', '');
    $("#clientName").combobox('setValue','');

    setBillOrderDetail();
    for (let i = 0; i < 12; i++) {
        $("#billgrid").edatagrid('appendRow', {});
    }
    // $('#billgrid').datagrid('loadData',{total:0,rows:[]})
    $("#saved").hide();
    $("#audited").hide();
    $("#invalid").hide();
}

//锁定订单页面为不可修改
function Orderlocking() {
    $("#billgrid").edatagrid('disableEditing');  //明细不可修改

    $("#billcode").textbox({disabled: true});
    $("#clientName").combobox("disable");
    $("#ddh").textbox({disabled: true});

}

function getDate(param) {
    if (isNaN(param)) {
        param = 0;
    }
    var curDate = new Date();
    var newDate = new Date(curDate);
    newDate.setDate(curDate.getDate() + param);
    var year = newDate.getFullYear();
    var month = newDate.getMonth() + 1 < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1;
    var date = newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate();
    var separator = '-';
    return year + separator + month + separator + date;
}


//关闭当前模态窗
function closeTabA() {
    $('#A').window('close');  // close a window
    ClearallorderBill();
    // refresh()
}


//获取所有下拉数据
function getdropdownDataA() {
    //设置客户下拉
    $.ajax({
        // dynamicQuery/querySqlString/select * from bill_type
        // url: strLin + 'contact/selectAll',
        url: strLin + 'dynamicQuery/querySqlString/select sid,sname,Fun_GetPY(sname)code from contact',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            $('#clientName').combobox({
                valueField: 'sid',
                textField: 'sname',
                data: cdata.data,
                panelWidth: 250,
                panelHeight: 400,
                missingMessage: '必输项,必须选择下拉菜单中的值,否则无法保存',
                // invalidMessage:'必输项,必须选择下拉菜单中的值,否则无法保存',
                idField: 'code',
                formatter: row => {
                    return row['sname'] + '-' + row['code'];
                },
                onSelect: row => {

                },
                filter: function (q, row) {
                    let options = $(this).combobox('options');
                    let textField = row[options.textField] || '';
                    let sIdField = row[options.valueField] || '';
                    let codeField = row[options.idField] || '';
                    // console.log(options);
                    return textField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0
                        || sIdField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0
                        || codeField.toString().toUpperCase().indexOf(q.toUpperCase()) >= 0;
                },
                onLoadSuccess: function () {
                    $(this).combobox('options').limitToList = true
                }
            });
            clientall = cdata.data
        }
    });

    //设置品名下拉
    $.ajax({
        url: strLin + 'product/selectAll',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            pinmingall = cdata.data
            // console.log(pinmingall)
            // setBillOrderDetail();
        }
    });
}


//作废原因保存
function tovoidMemoSaveC() {
    let tovoidMemo=$("#tovoidMemo").textbox('getValue');
    let pass=$("#passC").textbox('getValue');
    let detailBill = $("#billgrid").edatagrid("getRows");
    var strData=[];
    let orderDetailID;

    if (tovoidMemo==null || tovoidMemo=='' ||tovoidMemo== undefined){
        $.messager.defaults = {ok: "确定", width: 300, closable: false};
        $.messager.alert('提示','作废原因必输，为空不允许保存！')
        return;
    }
    if (pass==null || pass=='' ||pass== undefined){
        $.messager.defaults = {ok: "确定", width: 300, closable: false};
        $.messager.alert('提示','密码必输，为空不允许保存！')
        return;
    }

    $.ajax({
        url: strLin + "dynamicQuery/querySqlString/select * from sys_user where username='"+ username + "' and password='" + pass + "'",
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
              if (cdata.data.length>0){
                  console.log('密码正确');

                  for (let i = 0; i < detailBill.length; i++) {
                      if (detailBill[i].product_sid && detailBill[i].color && detailBill[i].kilo){
                          strData[i]={iid:detailBill[i].iid,state:0};
                          if (orderDetailID){
                              orderDetailID= orderDetailID +',' + detailBill[i].iid
                          }else{orderDetailID= detailBill[i].iid}
                      }
                  }

                  let SQL={"main":{"iid":m_orderID,"state":0,"nullify_remark":tovoidMemo},"details":strData}
                  console.log(SQL);
                  JudgeOrderPlan(orderDetailID,SQL);

              }else{
                  $.messager.defaults = {ok: "确定", width: 300, closable: false};
                  $.messager.alert('提示','密码错误！');
                  $("#passC").textbox("setValue", '');
                  return;
              }

        }
    });


    // $.ajax({
    //     url: strLin + 'billOrder/update',
    //     type: 'POST',
    //     dataType: 'json',
    //     data: JSON.stringify(SQL),
    //     contentType: "application/json;charset=UTF-8",
    //     success: function (cdata) {
    //         let data=cdata.data;
    //         console.log(data);
    //         ClearallorderBill();
    //         refresh();
    //         $('#C').window('close');
    //         $("#tovoidMemo").datebox("setValue", '');
    //     }
    // });
}

//作废原因取消保存
function tovoidMemocancelC() {
    $('#C').window('close');
    $("#tovoidMemo").textbox("setValue", '');
    $("#passC").textbox("setValue", '');
}

//判断当前订单明细是否有生成计划存在
function JudgeOrderPlan(orderdetailID,SQL) {
    $.ajax({
        url: strLin + 'dynamicQuery/querySqlString/select * from plan where state=1 and parent_id in ('+ orderdetailID +")",
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            let data=cdata.data;
            console.log(data);
            if (data.length>0){
                $.messager.defaults = {ok: "确定", width: 300, closable: false};
                $.messager.alert('提示','当前订单存在已生成计划单，不允许作废！');
                $('#C').window('close');
                $("#tovoidMemo").textbox("setValue", '');
                $("#passC").textbox("setValue", '');
                return;
            }else{
                $.ajax({
                    url: strLin + 'billOrder/update',
                    type: 'POST',
                    dataType: 'json',
                    data: JSON.stringify(SQL),
                    contentType: "application/json;charset=UTF-8",
                    success: function (cdata) {
                        let data=cdata.data;
                        console.log(data);
                        ClearallorderBill();
                        refresh();
                        $('#C').window('close');
                        $("#tovoidMemo").textbox("setValue", '');
                        $("#passC").textbox("setValue", '');
                    }
                });
            }

        }
    });

}